package com.commerce.reader.ui.home;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.commerce.reader.Entity.Book;
import com.commerce.reader.Entity.Books;

import org.litepal.LitePal;

import java.util.List;



import static com.commerce.reader.utils.JsoupHtml.toBookUrl;
import static com.commerce.reader.utils.JsoupHtml.toBooksUrl;

public class HomeViewModel extends ViewModel {
    private final static int UPDATE_MAP = 1;
    private MutableLiveData<Book> mBook;
    private Books books;
    private Book list;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case UPDATE_MAP:
                    mBook.setValue(list);
                    break;
                default:
            }
            super.handleMessage(msg);
        }
    } ;

    public HomeViewModel() {
        mBook = new MutableLiveData<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Books> all = LitePal.findAll(Books.class);
                if(all.size()==0){
                    toBooksUrl("http://www.xbiquge.la/xiaoshuodaquan/");
                    all = LitePal.findAll(Books.class);
                }
                books = all.get((int) (all.size() * Math.random()));
                list = toBookUrl(books.getUrl());
                Message message = new Message();
                message.what = UPDATE_MAP;
                handler.sendMessage(message);
                toBooksUrl("http://www.xbiquge.la/xiaoshuodaquan/");
            }
        }).start();
    }

    public LiveData<Book> getBook() {
        return mBook;
    }

    public Books randomBooks() {
        return books;
    }
}